package com.zany.net.codec;

import com.zany.net.MinaConvert;
import org.apache.log4j.Logger;
import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolDecoderOutput;
import org.apache.mina.filter.codec.demux.MessageDecoder;
import org.apache.mina.filter.codec.demux.MessageDecoderResult;

import java.io.UnsupportedEncodingException;

public class MyMessageDecoder implements MessageDecoder {
	private Logger logger = Logger.getLogger(MyMessageDecoder.class);

	public void finishDecode(IoSession session, ProtocolDecoderOutput out) throws Exception {
	} 


	public MessageDecoderResult decodable(IoSession session, IoBuffer in) {
		if(logger.isInfoEnabled()){logger.info("MyMessageDecoder.decodable()");}
		String string = null;
		try {
			string = MinaConvert.ioBufferToString(in);
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} 
		if(null==string || "".equals(string)){ 
		    return MessageDecoderResult.NEED_DATA;
		} 
		return MessageDecoderResult.OK;
	} 
	
	public MessageDecoderResult decode(IoSession session, IoBuffer in,
                                       ProtocolDecoderOutput out) throws Exception {
		String string = MinaConvert.ioBufferToString(in); 
		out.write(string); 
		return MessageDecoderResult.OK;
	} 
}
